from helpers import updateInfo
from helpers import Transactions
from helpers import Visualization
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Show report (user portfolio) page class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Check for msgs
        errorList=[]
        if self.request.get('msg'):
            errorList=updateInfo.buildErrorList(self.request.get('msg'))
        categoryName = "Your Portfolio"    
        # Sell stock selected
        if self.request.get('sells'):
            #need to check if we sell a stock or ETF
            try:
                q_1 = db.get(db.Key(self.request.get('sells')))
                
                if isinstance(q_1,updateInfo.Stocks):
                    if q_1.stockref!=None:
                        #deleteing stock
                        succ=Transactions.sellStock(user, q_1)
                        if succ==0:
                            errorList=updateInfo.buildErrorList("3")
                    else:
                        #deleting ETF
                        succ=Transactions.sellETF(user, q_1)
                        if succ==0:
                            errorList=updateInfo.buildErrorList("3")
            except:
                errorList=updateInfo.buildErrorList("3")
            
        # catch monkey        
        if self.request.get('monkey'):
            try:
                categoryName = "Investor's Portfolio" 
                user=users.User(updateInfo.getMonkeyName(int(self.request.get('monkey'))))
            except:
                self.redirect('/account?msg=1')
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        
        
        # Build Total Amount Graph
        graph_text=Visualization.buildUserGraph(user)
    
        # Load 100 stocks list of user from database
        q_2 = db.GqlQuery("SELECT * FROM Stocks " +
        "WHERE buyer = :1 ORDER BY buydate DESC LIMIT 0,100", user)
        
        # Init text to be used to print pieChart
        pieChartText=""
        
        # Decide if to show stocks table (if user hasn't bought stocks yet)
        showTable=0
        if q_2.count()>0:
            showTable=1
        
        # Init text to be used to print stocks table
        table_stocks_Text="\ndata.addRows(%d);\n" % (q_2.count())
        
        # Iterate over stocks list
        # Will be used to build the stocks table and pieChart
        
        i=0
        for p in q_2:
            if p.basketref==None:
                stockname=p.stockref.stockname
                reportvar=stockname
                category=p.stockref.categoryref.category
                # For future version, different cases in case of isProfile
                #if p.stockref.isProfile:
                    #stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#000000">%s</a>' % (str(p.stockref.key()),stockname)
                #else:
                    # changed to href - originally was stockname (omri)
                    #stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#000000">%s</a>' % (str(p.stockref.key()),stockname)
                stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#3366CC">%s</a>' % (str(p.stockref.key()),stockname)
            else:
                stockname=p.categoryref.category
                reportvar=""
                for stock in p.basketref.stocklist:
                    reportvar+="%s" % db.get(stock).stockname
                    reportvar+="%7C"
                #if p.basketref.isProfile:
                    #stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#000000">%s</a>' % (str(p.basketref.key()),stockname)
                #else:
                    #stocknameLink=stockname
                stocknameLink='<a href="/trendProfile?TKey=%s" style="color:#3366CC">%s</a>' % (str(p.basketref.key()),stockname)
                category="ETF"
                
            buyDate=p.buydate.strftime("%Y-%m-%d")
    
            table_stocks_Text+="data.setCell(%d, 0,'%s','%s',{style:'font-weight:bold;'});\n" % (i,stockname, stocknameLink)
            table_stocks_Text+="data.setCell(%d, 1, %s,'%s',{style: 'text-align: center;'});\n" % (i,buyDate.replace('-',''), buyDate)
            table_stocks_Text+="data.setCell(%d, 2, %.2f,'$%.2f');\n" % (i,p.buyValue, p.buyValue)

                
            # Date not available yet
            if p.yahooupdatedate==None and p.userupdatedate==None:
                table_stocks_Text+="data.setCell(%d, 3, 0,'(%%0.00)');\n" % (i)
                table_stocks_Text+="data.setCell(%d, 4, %.2f,'$%.2f');\n" % (i,p.buyValue, p.buyValue)
                table_stocks_Text+="data.setCell(%d, 5, 0,'No Data Yet',{style: 'font-weight:bold;text-align: center;'});\n" % (i)
                currentvalue=p.buyValue
            
            # Date is available
            else:
                if (p.yahooupdatedate!=None and p.userupdatedate!=None):
                    if p.yahooupdatedate>p.userupdatedate:
                        updateDate=p.yahooupdatedate.strftime("%y-%m-%d (%H:%M)")
                        updateDateNum=p.yahooupdatedate.strftime("%m%d")
                    else:
                        updateDate=p.userupdatedate.strftime("%y-%m-%d (%H:%M)")
                        updateDateNum=p.userupdatedate.strftime("%m%d")
                elif (p.yahooupdatedate!=None):
                        updateDate=p.yahooupdatedate.strftime("%y-%m-%d (%H:%M)")
                        updateDateNum=p.yahooupdatedate.strftime("%m%d")
                elif (p.userupdatedate!=None):
                        updateDate=p.userupdatedate.strftime("%y-%m-%d (%H:%M)")
                        updateDateNum=p.userupdatedate.strftime("%m%d")
                    
                percentCng=p.userPrecentChange
                currentvalue=p.currValue
                printPercentage, fontColor, changeSign= updateInfo.getPerInfo(percentCng)
                    
                table_stocks_Text+="data.setCell(%d, 3, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i,percentCng, changeSign,printPercentage,fontColor)
                table_stocks_Text+="data.setCell(%d, 4, %.2f,'$%.2f');\n" % (i,currentvalue, currentvalue)
                table_stocks_Text+="data.setCell(%d, 5, %s,'%s',{style: 'font-weight:bold;text-align: center;'});\n" % (i,updateDateNum,updateDate)
    
            table_stocks_Text+="data.setCell(%d, 6,'%s');\n" % (i,category)
            if self.request.get('monkey'):
                table_stocks_Text+="data.setCell(%d, 7,'<a href=\"\/buy?q=%s\" class=\"sell\">Buy</a>');\n" % (i,stockname)
            else:
                table_stocks_Text+="data.setCell(%d, 7,'<a href=\"\/report?sells=%s\" class=\"sell\">Sell</a>');\n" % (i,p.key())
            
                
            pieChartText+="['%s',%.2f]," % (stockname, currentvalue)
            i=i+1
    
        # Add Univested money to pieChart
        pieChartText+="['Uninvested Money',%.2f]" % (current_user.bankamount)
        
        piename=user.nickname().capitalize()
        
        if self.request.get('monkey'):
            user=users.get_current_user()
            current_user=updateInfo.getCurrentUser(user)
            
        template_values = {
            'pieChartText': pieChartText,
            'table_stocks_Text': table_stocks_Text,
            'graph_text': graph_text,
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'showTable' : showTable,
            'piename' : piename,
            'errorList' : errorList,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'categoryName' : categoryName+' %s' % updateInfo.createToolTip("portfolio"),
            'setHead' : 1,
            'headContent' : 'report_head.html',
            'maincontent' : 'account_main.html',
            'account_main_content' : 'report_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))

    def post(self):
     
        # Handle all forms submittions
        
        # Load main page again (Using PRG- Post/Redirect/Get)
        self.redirect('/report')
        return

application = webapp.WSGIApplication(
                                     [('/report', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
